import os

from litemall.web_ui.frame.utils.log_utils import logger
from litemall.web_ui.frame.utils.utils import Utils
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait



class BasePage:
    """
    基类：完成初始化浏览器，登录，及常用方法的封装
    """

    def __init__(self, driver=None):
        if driver:
            self.driver = driver
        else:
            self.driver = webdriver.Chrome()
            self.driver.maximize_window()
            self.driver.implicitly_wait(3)

            # 登录页面：输入用户名、密码点击登录
            self.driver.get("http://litemall.hogwarts.ceshiren.com/#/login?redirect=%2Fdashboard")
            self.driver.find_element(By.NAME, "username").clear()

            #读取yaml文件
            path = Utils.get_frame_root_path() +"/config/data.yaml"
            yamldatas = Utils.get_yaml_data(path)

            username = "manage"
            password = "manage123"

            if os.getenv("user"):
                _env = os.getenv("user")
                username = yamldatas.get('login').get(_env).get('username')
                password = yamldatas.get('login').get(_env).get('password')

            self.driver.find_element(By.NAME, "username").send_keys(username)
            self.driver.find_element(By.NAME, "password").clear()
            self.driver.find_element(By.NAME, "password").send_keys(password)
            self.driver.find_element(By.XPATH, "//*[text()='登录']").click()

    def do_find(self, by, locate=None):
        # 查找单个元素
        if locate:
            logger.info(f"查找元素：{locate}")
            return self.driver.find_element(by, locate)
        else:
            logger.info(f"查找元素：{by}")
            return self.driver.find_element(*by)

    def do_click(self, by, locate=None):
        # 点击按钮
        if locate:
            logger.info(f"点击元素:{locate}")
            self.driver.find_element(by, locate).click()
        else:
            logger.info(f"点击元素：{by}")
            self.driver.find_element(*by).click()

    def do_send_keys(self, value, by, locate=None):
        # 输入数据
        if locate:
            logger.info(f"向输入框：{locate}输入数据：{value}")
            self.driver.find_element(by, locate).clear()
            self.driver.find_element(by, locate).send_keys(value)
        else:
            logger.info(f"向输入框：{by}输入数据：{value}")
            self.driver.find_element(*by).clear()
            self.driver.find_element(*by).send_keys(value)

    def do_quit(self):
        #退出浏览器
        self.driver.quit()

    def wait_element_visible(self,by,locate=None):
        if locate:
            return WebDriverWait(self.driver, 10).until(
                expected_conditions.visibility_of_element_located((by, locate)))
        else:
            return WebDriverWait(self.driver, 10).until(
                expected_conditions.visibility_of_element_located(by))
